# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import time
from scrapy.http import HtmlResponse
from selenium.common.exceptions import TimeoutException

class ScrapyfundajjSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class ScrapyfundajjDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

#在下载器中间件中修改User-Agent的值，伪装成不同的浏览器
class RandomUserAgentMiddleware():
    def __init__(self,UA):
        self.user_agents = UA

    @classmethod
    def from_crawler(cls, crawler):
        return cls(UA = crawler.settings.get('MY_USER_AGENT'))

    def process_request(self,request,spider):
        request.headers['User-Agent'] = random.choice(self.user_agents)

    def process_response(self,request, response, spider):
        return response

class SeleniumMiddleware():
    #通过类方法from_crawler获取的参数必须放在__init__()方法的第一个参数位置上，除self；否则报错
    def __init__(self, MP,timeout=30 ):
        self.timeout = timeout
        self.browser = webdriver.Chrome()
        self.browser.maximize_window()
        self.browser.set_page_load_timeout(self.timeout)
        self.wait = WebDriverWait(self.browser,self.timeout)
        self.MAX_PAGE = MP

    @classmethod
    def from_crawler(cls, crawler):
        return cls(MP = crawler.settings.get('MAX_PAGE'))


    def process_request(self, request, spider):
        '''
        1、在下载器中间件中对接使用selenium，输出源代码之后，构造htmlresponse对象，直接返回给spider解析页面，提取数据,并且也不在执行下载器下载页面动作

        2、通过下载器执行器下载数据，不在通过selenium

        3、当网址是http://fund.10jqka.com.cn/datacenter/jz/时，因无法直接获取网页源代码，使用selenim直接回去源代码返回的方式处理，
           当网址是http://fund.10jqka.com.cn/000074/historynet.html#historynet类型时，使用框架的下载器下载数据，返回给spider文件处理
           通过获取spider文件的url，根据url判断是否使用selenium下载数据
        '''
        url = request.url
        if url.endswith("historynet.html#historynet"):
            return None
        else:
            self.wait = WebDriverWait(self.browser, self.timeout)
            try:

                time.sleep(5)
                self.browser.get(request.url)

                #MAX_PAGE暂时先写死，在settings中配置 可以写成动态变量
                #思路：观察目标网站，不断下拉滚动条加载新数据，每页80条数据，可以第一次获取页面总共有多少只基金产品总数据，
                #除以80即为需要下拉的次数
                for i in range(1, self.MAX_PAGE):
                    #执行js代码，将滚动条下拉到最下面
                    self.browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
                    time.sleep(2)

                time.sleep(5)
                response = self.browser.page_source
                return HtmlResponse(url=request.url, body=response, request=request, encoding='utf-8',status=200)
            except TimeoutException:
                return HtmlResponse(url=request.url, status=500, request=request)
            finally:
                self.browser.close()

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)